<template>
  <div class="start-approval">
    <a-row>
      <a-col :span="10" :offset="7" class="bg-white card">
        <a-page-header
          style="padding:0"
          :title="detail.name"
          @back="$router.back()"
        />
        <div class="title">
          <div class="desc">发起{{ detail.name }}申请</div>
        </div>
        <a-divider style="margin: 12px 0" />
        <div v-if="detail.banner_img" style="width: 100%;margin-bottom: 10px;">
          <img :src="detail.banner_img" style="width: 100%;">
        </div>
        <div class="form">
          <a-form layout="vertical" :scrollToFirstError="true">
            <a-form-item
              label="所属部门"
              v-bind="validateInfos.department_id"
              v-if="departmentList.length > 1"
            >
              <a-select
                :options="departmentList"
                v-model:value="formState.department_id"
                @change="(val, opt) => handleDepartmentChange(opt)"
              />
            </a-form-item>
            <template v-for="formItem of formList" :key="formItem.key">
              <div v-if="formItem.type == 'tips'" class="form-tip">
                <span>{{ formItem.setting.placeholder }}</span>
              </div>

              <template v-else-if="formItem.type == 'detail' && formItem.value">
                <a-card
                  class="detail"
                  :title="formItem.setting.name"
                  size="small"
                  :headStyle="{background: '#f7f7f7'}"
                >
                  <!-- <template #extra>
                    <a-button type="link" @click="addDetailItem(formItem)">
                      <template #icon>
                        <PlusOutlined />
                      </template>
                      添加{{ formItem.setting.name }}
                    </a-button>
                  </template> -->
                  <a-card
                    size="small"
                    v-for="(formItemList, listIndex) of formItem.value"
                    :key="listIndex"
                    :style="listIndex > 0 ? 'margin-top: 10px' : ''"
                  >
                    <template #title>
                      <span class="bold">#{{ listIndex + 1 }}</span>
                    </template>
                    <template #extra>
                      <a-button
                        type="link"
                        danger
                        @click="removeDetailItem(formItem.value, listIndex)"
                        :disabled="listIndex == 0"
                      >
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </template>
                    <a-row :gutter="12">
                      <a-col
                        :span="24"
                        v-for="formItem2 of formItemList"
                        :key="formItem2.key"
                      > 
                        <div v-if="formItem2.type == 'tips'" class="form-tip">
                          <span>{{ formItem2.setting.placeholder }}</span>
                        </div>
                        <a-form-item
                          v-else
                          v-bind="validateInfos[formItem2.key]"
                        >
                          <template #label>
                            <span>{{ formItem2.setting.name }}</span>
                            <span v-if="formItem2.setting.unit">
                              （{{ formItem2.setting.unit }}）
                            </span>
                          </template>
                          <form-item
                            :content="formItem2"
                            :list="formItemList"
                            :form="formState"
                            @change="formStateChange"
                          />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                  <a-button
                    type="primary"
                    ghost
                    @click="addDetailItem(formItem)"
                    style="width: 100%; margin-top: 20px"
                  >
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    添加
                    <!-- {{ formItem.setting.name }} -->
                  </a-button>
                </a-card>
              </template>
              <a-form-item v-else v-bind="validateInfos[formItem.key]">
                <template #label>
                  <span>{{ formItem.setting.name }}</span>
                  <span v-if="formItem.setting.unit">
                    （{{ formItem.setting.unit }}）
                  </span>
                </template>
                <form-item
                  :content="formItem"
                  :list="formList"
                  :form="formState"
                  @change="formStateChange"
                  @build-change="changeProject"
                />
              </a-form-item>
            </template>
            <ProcessStep :process="process"/>
            <a-form-item>
              <a-space>
                <a-button
                  type="primary"
                  @click="submit"
                  :loading="submitLoading"
                >
                  提交
                </a-button>
                <a-button @click="$router.back()"> 取消 </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { defineComponent, reactive, toRaw, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { Form, message } from "ant-design-vue";
import FormItem from "./modules/FormItem.vue";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import ProcessStep from "./modules/ProcessStep.vue";
import store from '@/store'
const useForm = Form.useForm;

export default defineComponent({
  name: "StartApproval",
  components: { FormItem, ProcessStep, PlusOutlined, DeleteOutlined },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      id: Number(route.query.id),
      detail: {},
      originFormList: [],
      formList: [],
      departmentList: [],
      process: [],
      controls: [],
      submitLoading: false,
      banner_img:'',
      village_id:undefined,
    });

    const formState = reactive({
      department_id: undefined,
      department_name: "",
    });
    const requiredRule = [{ required: true, message: "必填项" }];
    const rules = reactive({
      department_id: requiredRule,
    });

    const { resetFields, validate, validateInfos } = useForm(formState, rules);

    const formStateChange = () => {
      if (!process.length) {
        getProcessDetail();
      }
    };

    const getOriginFormItem = (formList, originFormList) => {
      let originItem = {};
      let result = [];
      for (let i in formList) {
        const item = formList[i];
        if (item.originKey) {
          if (originItem[item.originKey]) {
            originItem[item.originKey].value[item.typeKey] = item.value;
          } else {
            const oItem = originFormList.find(
              (item2) => item2.key == item.originKey
            );
            originItem[item.originKey] = oItem;
            originItem[item.originKey].value = {
              [item.typeKey]: item.value,
            };
          }
          const filterRes = result.filter(it=>{
            console.log(it)
            return it.key==item.originKey
          })
          if (filterRes.length==0){
            result.push(originItem[item.originKey]);
          }else {
            result.forEach((resItem,index)=>{
              if (resItem.key==item.key){
                result[index]= originItem[item.originKey]
              }
            })
          }
        } else {
          if (item.type == "detail") {
            const oFormList = state.originFormList.find(
              (it) => it.key == item.key
            );
            item.formList = getOriginFormItem(
              item.formList,
              oFormList.formList
            );
            item.value = item.value.map((item2) => {
              return getOriginFormItem(item2, oFormList.formList);
              // let newItem = {};
              // for (let item3 of item2) {
              //   const key = item3.key.split("#")[0];
              //   newItem[key] = item3.value;
              // }
            });
          }
          result.push(item); 
        }
      }
      return result;
    };

    const submit = () => {
      console.log("---------------------submit11111", toRaw(formState));
      console.log("---------------------submit2222", toRaw(state.formList));
      console.log(
        "---------------------submit3333",
        toRaw(state.originFormList)
      );
      validate()
        .then(() => {
          console.log("---------------------submit", toRaw(formState));
          state.submitLoading = true;
          const params = {
            approval_id: state.id,
            department_id: formState.department_id,
            department_name: formState.department_name,
            form: [],
            process: state.process,
            controls: state.controls,
            needMsg: true,
          };

          const formList = JSON.parse(JSON.stringify(state.formList));
          params.form = getOriginFormItem(formList, state.originFormList);
          console.log(
            "---------------------submit----------------------",
            toRaw(params)
          );
          request
            .post("/work_approval", "/staff/approval/form", params)
            .then((res) => {
              message.success(res.msg || "提交成功！");
              router.replace({
                name: "ApprovalDetail",
                query: { id: res.data.id,isBack: true },
              });
            })
            .finally(() => {
              state.submitLoading = false;
            });
        })
        .catch((err) => {
          console.log("------------err", err);
          message.warning("有必填项未填写！");
        });
    };

    // 添加明细
    let addCount = 1;
    const addDetailItem = (detailItem) => {
      addCount++;
      let newItem = JSON.parse(JSON.stringify(detailItem.formList));
      transformForm(newItem, addCount);
      detailItem.value.push(newItem);
      // console.log("---addDetailItem", toRaw(detailItem.value));
    };

    // 移除明细
    const removeDetailItem = (currentForm, index) => {
      const current = currentForm[index];
      // console.log("---current", current);
      for (let item of current) {
        delete formState[item.key];
        delete rules[item.key];
      }
      currentForm.splice(index, 1);
    };

    const transformForm = (formList, suffix = "") => {
      for (let formItem of formList) {
        const { type, key, setting } = formItem;
        let formKey = suffix ? `${key}#${suffix}` : key;
        formItem.key = formKey;
        if (type == "detail") {
          transformForm(formItem.value[0], 1);
        } else if (["check", "image", "file"].includes(type)) {
          formState[formKey] = [];
        } else {
          formState[formKey] = setting.setDefault ? setting.defaultValue : "";
        }
        if (!rules[formKey]) {
          if (type == "phone") {
            rules[formKey] = [
              {
                required: setting.required,
                validator: (rules, value) => utils.phoneValidator(rules, value),
              },
            ];
          } else {
            rules[formKey] = setting.required ? requiredRule : [];
          }
        }
      }
    };

    const getApprovalDetail = () => {
      request
        .get("/work_approval", "/staff/approval/detail", {
          id: state.id,
        })
        .then((res) => {
          state.detail = res.detail;
          state.originFormList = JSON.parse(JSON.stringify(res.detail.form));
          state.formList = [];
          res.detail.form.forEach((item) => {
            if (item.type == "daterange") {
              const result = handleDateRange(item);
              state.formList = [...state.formList, ...result];
            } else {
              if (item.type == "detail") {
                handleDetailControl(item);
              }
              state.formList.push(item);
            }
            if (item.type=="project"){
              store.dispatch("SetVillageList")
            }
          });
          transformForm(state.formList);
        });
    };
    // detail 明细组件数据整理
    const handleDetailControl = (item) => {
      let formList = [];
      item.formList.forEach((item) => {
        if (item.type == "daterange") {
          const result = handleDateRange(item);
          formList = [...formList, ...result];
        } else {
          formList.push(item);
        }
      });
      item.formList = formList;
      item.value = [JSON.parse(JSON.stringify(formList))];
    };
    // date range数据整理
    const handleDateRange = (item) => {
      let result = [];
      let nameArr = item.name || item.setting.name;
      for (let i in nameArr) {
        let newItem = {
          originKey: item.key,
          originType: item.type,
          key: `${item.key}_${i}`,
          name: nameArr[i],
          setting: {
            name: nameArr[i],
            placeholder: item.setting.placeholder,
            required: item.setting.required,
            dateType: item.setting.dateType,
          },
        };
        if (i < 2) {
          newItem.type = "date";
          newItem.typeKey = i == 0 ? "start" : "end";
        } else {
          newItem.type = "number";
          newItem.typeKey = "duration";
          newItem.setting.unit = "天";
          newItem.setting.placeholder = "自动计算";
          newItem.setting.disabled = !item.setting.durationChange;
        }
        result.push(newItem);
      }
      return result;
    };

    const getProcessDetail = () => {
      request
        .get("/work_approval", "/staff/approval/process", {
          id: state.id,
          department_id: formState.department_id,
          village_id:state.village_id?state.village_id:undefined,
        })
        .then((res) => {
          state.process = res.process;
          state.controls = res.controls;
        });
    };

    const getDepartmentList = () => {
      request.get("/org", "/user/department/list").then((res) => {
        if (res.list.length) {
          state.departmentList = res.list.map((item) => ({
            value: item.id,
            label: item.name,
          }));
          handleDepartmentChange(state.departmentList[0]);
        } else {
          state.departmentList = [];
          formState.department_id = 0;
          formState.department_name = "";
        }
      });
    };
    const handleDepartmentChange = (option) => {
      formState.department_id = option.value;
      formState.department_name = option.label;
    };

    const init = () => {
      getApprovalDetail();
      getDepartmentList();
    };

    init();

    const changeProject = (val) => {
      state.village_id = val
      getProcessDetail()
    }

    return {
      formState,
      validateInfos,
      ...toRefs(state),
      submit,
      handleDepartmentChange,
      addDetailItem,
      removeDetailItem,
      formStateChange,
      changeProject,
    };
  },
});
</script>

<style lang="less" scoped>
.start-approval {
  width: 100%;
  min-height: 100%;
  background: #f7f7f7;
  padding: 20px 0;
  .card {
    padding: 20px;
    border-radius: 10px;
    .title {
      .name {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 1);
      }
      .desc {
        color: rgba(0, 0, 0, 0.5);
        line-height: 30px;
      }
    }
    .form-tip {
      padding: 10px;
      background: #f1f1f1;
      margin-bottom: 16px;
      color: #000;
    }
    .detail {
      // border: 1px solid red;
      margin-bottom: 20px;
    }
  }
}
</style>
